<?php

class Materials_Model_Label_Storage_Table extends Workset_Model_Object_Storage_Table_Abstract {

	protected $_objectClass 		= 'Materials_Model_Label';

	protected $_tableClass 			= 'Materials_Table_Label';

	protected $_iteratorClass 		= 'Workset_Model_Object_Iterator';

    protected $_material2LabelTableClass  = 'Materials_Table_Material2Label';


    function linkToObject(Workset_Model_Object_Interface $object, Workset_Model_Object_Interface $refObject) {

        $row = $object->getData();
        if ($row instanceof Workset_Db_Table_Row) {

            return $row->addDependentRow($this->_material2LabelTableClass, array(
                'material_id' => $refObject->getId(),
            ));

        }
    }

    function unlinkObject(Workset_Model_Object_Interface $object, Workset_Model_Object_Interface $refObject) {
        $row = $object->getData();
        if ($row instanceof Workset_Db_Table_Row) {

            $subrow = $row->findDependentRow($this->_material2LabelTableClass, 'label', array(
                'material_id = ?' => $refObject->getId(),
            ));

            if ($subrow) {
                return $subrow->delete();
            } else {
                throw new Zend_Exception('Undefined reference to object '.get_class($refObject));
            }
        }
    }

    function materialsCount(Workset_Model_Object_Interface $object, $where = null) {

        $table = $this->_getTable($this->_material2LabelTableClass);
        $select = $table->select();
        $where = (array)$where;
        $where['label_id = ?'] = $object->getId();

        $select->from(
            $table->info(Zend_Db_Table::NAME),
            array('cnt' => new Zend_Db_Expr('COUNT(*)'))
        );

        foreach ($where as $key => $value) {
            if (isInt($key)) {
                $select->where($value);
            } else {
                $select->where($key, $value);
            }
        }

        return $table->getAdapter()->fetchOne($select);
    }

}